import React, { useEffect, useState, useCallback } from 'react';
import { default as useFetchList } from '@/hooks/getList';
import useFetchData from '@/hooks/getData';
import {
  Card,
  Table,
  TableColumnProps,
  Grid,
  Space,
  Button,
  Form,
  Input,
  Select,
  Message,
  Popconfirm,
  Descriptions,
  Drawer,
  Typography,
} from '@arco-design/web-react';
import {
  getUserPage,
  addUser,
  editUser,
  deleteUser,
  getRelationctlUser,
  resetUserPassword,
  getUserDetail,
} from '@/api/userData';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import AddOrEditForm from '@/pages/userManagement/backendUserList/components/addOrEditBox';

dayjs.extend(utc);

const FormItem = Form.Item;
const Row = Grid.Row;
const Col = Grid.Col;

const statusOptions = [
  { label: '在职', value: 1 },
  { label: '离职', value: 2 },
];

function BackendUser() {
  const { data, pagination, loading, getData } = useFetchList(getUserPage, {});

  // 企业账号关联
  const { data: relationUserList, getData: getRelationUser } = useFetchData(
    getRelationctlUser,
    {}
  );

  useEffect(() => {
    getRelationUser();
  }, []);

  const [searchParams, setSearchParams] = useState({
    Name: null,
    Account: null,
    QueryStatus: null,
  });

  const onSearch = useCallback((values) => {
    pagination.current = 1;
    values.Name ??= null;
    values.Account ??= null;
    values.QueryStatus ??= null;
    setSearchParams(values);
    getData({ ...values, PageIndex: pagination.current });
  }, []);

  const onChangeTable = useCallback(
    (pagination) => {
      const { current, pageSize } = pagination;
      const obj = {
        PageIndex: current,
        PageSize: pageSize,
      };
      const newObj = Object.assign(obj, searchParams);
      getData(newObj);
    },
    [searchParams]
  );

  const [modalVisible, setModalVisible] = useState(false);
  const [editData, setEditData] = useState(null);
  const [formModalShowType, setFormModalShowType] = useState('add');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const handleChangeVisible = useCallback((visible) => {
    setModalVisible(visible);
  }, []);

  const handleEdit = async (record) => {
    const res: any = await getUserDetail({
      Id: record.ID,
    });
    if (res.StatusCode === 200) {
      const resData = res.Result;
      let RelationUserIds = [];
      if (resData.RelationUsers && resData.RelationUsers.length !== 0) {
        RelationUserIds = resData.RelationUsers.map((item) => item.CTLUserId);
      }
      const data = {
        ID: resData.ID,
        Account: resData.Account,
        Status: resData.Status,
        CTLUserId: resData.CTLUserId,
        CTLUserName: resData.CTLUserName,
        Name: resData.Name,
        PhoneNumber: resData.PhoneNumber,
        ResignDate: resData.ResignDate,
        RelationUserIds,
      };
      setEditData(data);
      setFormModalShowType('edit');
      setModalVisible(true);
    } else {
      Message.error(res.Message);
    }
  };

  // 新增/编辑提交
  const onConfirm = useCallback(
    async (reqData: any, relationList) => {
      // 在职
      if (reqData.Status === 1) {
        reqData.ResignDate = null;
        const CTLUserName = relationList.find(
          (item: any) => item.CTLUserId === reqData.CTLUserId
        ).CTLUserName;

        reqData.CTLUserName = CTLUserName;
      } else {
        reqData.CTLUserId = '';
        reqData.CTLUserName = '';
        const utcDate = new Date(reqData.ResignDate).toISOString();
        reqData.ResignDate = utcDate;
      }

      let res;

      if (formModalShowType === 'add') {
        res = await addUser(reqData);
      } else {
        res = await editUser(reqData);
      }

      if (res.StatusCode === 200) {
        handleChangeVisible(false);
        Message.success(res.Message);
        setEditData({});
        getData();
      } else {
        Message.error(res.Message);
      }
    },
    [formModalShowType]
  );

  // 关闭新增/编辑弹窗
  const onCancel = useCallback(() => {
    setEditData({});
  }, []);

  /**
   * 查看详情
   */
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [detailData, setDetailData] = useState([]);
  const getDataDetail = useCallback(
    async (item) => {
      const res: any = await getUserDetail({
        Id: item.ID,
      });
      if (res.StatusCode === 200) {
        setDetailData(res.Result);
        setDetailModalVisible(true);
      } else {
        Message.error(res.Message);
      }
    },
    [detailData]
  );

  const handleDetailVisible = useCallback((visible) => {
    setDetailModalVisible(visible);
  }, []);

  const columns: TableColumnProps[] = [
    {
      title: '序号',
      dataIndex: 'ID',
      align: 'center',
      render: (col, item: any, index: number) => index + 1,
    },
    {
      title: '用户账号',
      dataIndex: 'Account',
      align: 'center',
    },
    {
      title: '用户名称',
      dataIndex: 'Name',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'Status',
      align: 'center',
      render: (col, item: any, index: number) => {
        return col === 1 ? (
          <Typography.Text type="success">在职</Typography.Text>
        ) : (
          <Typography.Text type="error">离职</Typography.Text>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'op',
      align: 'center',
      fixed: 'right',
      render: (_, record) => (
        <div>
          <Button
            type="text"
            onClick={() => handleEdit(record)}
            disabled={record.IsForSystem}
          >
            编辑
          </Button>
          <Button
            type="text"
            disabled={record.IsForSystem}
            onClick={() => {
              getDataDetail(record);
            }}
          >
            查看详情
          </Button>
        </div>
      ),
    },
  ];

  useEffect(() => {
    getData();
  }, []);

  return (
    <div>
      <Card style={{ marginBottom: 20 }}>
        <Row>
          <Space direction="vertical">
            <Col>
              <Space size="large">
                <Button
                  type="primary"
                  onClick={() => {
                    setEditData({ Status: 1 });
                    setModalVisible(true);
                    setFormModalShowType('add');
                  }}
                >
                  新增
                </Button>
                <Popconfirm
                  position="bottom"
                  focusLock
                  title="提示"
                  content="是否确认重置初始密码？"
                  onOk={async () => {
                    if (selectedRowKeys.length === 0) {
                      Message.error({
                        content: '请选择需要重置初始密码的用户',
                      });
                      return;
                    }
                    const res: any = await resetUserPassword({
                      Ids: selectedRowKeys,
                    });

                    if (res.StatusCode === 200) {
                      Message.success(res.Message);
                      setSelectedRowKeys([]);
                    } else {
                      Message.error(res.Message);
                    }
                  }}
                >
                  <Button>重置初始密码</Button>
                </Popconfirm>
                <Popconfirm
                  position="bottom"
                  focusLock
                  title="提示"
                  content="是否确定删除？"
                  onOk={async () => {
                    if (selectedRowKeys.length === 0) {
                      Message.error({
                        content: '请选择需要删除的用户',
                      });
                      return;
                    }
                    const res: any = await deleteUser({
                      Ids: selectedRowKeys,
                    });

                    if (res.StatusCode === 200) {
                      Message.success(res.Message);
                      getData();
                    } else {
                      Message.error(res.Message);
                    }
                  }}
                >
                  <Button>删除</Button>
                </Popconfirm>
              </Space>
            </Col>
            <Col>
              <Search getSearchData={onSearch} />
            </Col>
          </Space>
        </Row>
      </Card>
      <Card>
        <Table
          border
          borderCell
          scroll={{
            x: 1600,
            y: 500,
          }}
          rowSelection={{
            type: 'checkbox',
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedRowKeys(selectedRowKeys);
            },
            checkboxProps: (record) => {
              return {
                disabled: record.IsForSystem,
              };
            },
          }}
          columns={columns}
          pagination={pagination}
          data={data}
          loading={loading}
          onChange={onChangeTable}
          rowKey="ID"
        />
      </Card>

      <AddOrEditForm
        visible={modalVisible}
        editData={editData}
        modalTitle={formModalShowType === 'add' ? '新增教师' : '编辑教师'}
        formModalShowType={formModalShowType}
        relationUserList={relationUserList}
        handleChangeVisible={handleChangeVisible}
        onConfirm={onConfirm}
        onCancel={onCancel}
      ></AddOrEditForm>

      <DetailModal
        visible={detailModalVisible}
        detailData={detailData}
        modalTitle="用户详情"
        handleChangeVisible={handleDetailVisible}
      ></DetailModal>
    </div>
  );
}

function Search({ getSearchData }) {
  const [form] = Form.useForm();
  const reset = () => {
    form.resetFields();
    getSearchData({});
  };
  return (
    <Form
      layout="inline"
      form={form}
      initialValues={{ name: 'admin' }}
      autoComplete="off"
      onSubmit={(values) => {
        getSearchData(values);
      }}
      style={{ marginTop: '20px' }}
    >
      <FormItem label="用户账号" field="Account">
        <Input placeholder="请输入" allowClear />
      </FormItem>
      <FormItem label="用户名称" field="Name">
        <Input placeholder="请输入" allowClear />
      </FormItem>
      <FormItem label="状态" field="QueryStatus">
        <Select
          allowClear
          placeholder="请选择"
          options={statusOptions}
          onChange={() => {
            form.submit();
          }}
          autoWidth={{ minWidth: 200, maxWidth: 500 }}
        ></Select>
      </FormItem>
      <FormItem>
        <Space>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button onClick={reset}>重置</Button>
        </Space>
      </FormItem>
    </Form>
  );
}

function DetailModal(props: any) {
  const { visible, modalTitle, detailData, handleChangeVisible } = props;

  const changeVisible = () => {
    handleChangeVisible(false);
  };

  const [listDetail, setListDetail] = useState([]);

  useEffect(() => {
    if (!visible) return;
    const detail = [
      {
        label: '用户账号',
        value: detailData.Account,
      },
      {
        label: '用户名称',
        value: detailData.Name,
      },
      {
        label: '手机号码',
        value: detailData.PhoneNumber,
      },
      {
        label: '用户账号',
        value: detailData.Account,
      },
      {
        label: '状态',
        value: detailData.Status === 1 ? '在职' : '离职',
      },
      {
        label: '离职时间',
        value: detailData.ResignDate,
      },
      {
        label: '创建人',
        value: detailData.CreateUserName,
      },
      {
        label: '创建时间',
        value: detailData.CreatedOn,
      },
      {
        label: '关联子账号',
        value: detailData.CTLUserName,
      },
    ];
    const filterData = detail.filter(
      (item) => item.value !== null && item.value !== ''
    );
    setListDetail(filterData);
  }, [visible]);

  const columns: TableColumnProps[] = [
    {
      title: '校园账号',
      dataIndex: 'CTLAccount',
      align: 'center',
    },
    {
      title: 'C端用户名',
      dataIndex: 'CTLUserName',
      align: 'center',
    },
  ];

  return (
    <Drawer
      title={modalTitle}
      visible={visible}
      autoFocus={false}
      focusLock={false}
      onOk={changeVisible}
      onCancel={changeVisible}
      width={500}
    >
      <div style={{ marginBottom: 10 }}>基础资料</div>
      <Descriptions
        column={1}
        data={listDetail}
        labelStyle={{ textAlign: 'right', paddingRight: 36 }}
      />
      <div style={{ marginTop: 20 }}>
        管控账户
        <Table
          borderCell
          border
          rowKey="CTLUserId"
          columns={columns}
          data={detailData.RelationUsers}
          pagination={false}
          scroll={{
            y: 460,
          }}
        />
      </div>
    </Drawer>
  );
}

export default BackendUser;
